var express = require('express');
const { GoodModel } = require("../model/db")
var router = express.Router();
var path = require("path")
var multiparty = require("multiparty")
var fse = require("fs-extra")
var bodyParser = require('body-parser')
router.post("/getg", async (req, res) => {
    let { cate, brand, area, storage, page, pageSize, m, name } = req.body
    let type
    let isup
    if (m) {
        type = m.type
        isup = m.isup
    }
    let arr = []
    if (cate) {
        let regcate = new RegExp(cate)
        arr.push({
            cate: regcate
        })
    }
    if (brand) {
        let regbrand = new RegExp(brand)
        arr.push({
            brand: regbrand
        })
    }
    if (area) {
        let regarea = new RegExp(area)
        arr.push({
            area: regarea
        })
    }
    if (storage) {
        let regstorage = new RegExp(storage)
        arr.push({
            storage: regstorage
        })
    }
    if (name) {
        let regname = new RegExp(name)
        arr.push({
            name: regname
        })
    }
    let list = await GoodModel.find({
        $and: arr
    })
    let total = await GoodModel.find({
        $and: arr
    }).countDocuments()
    if (type == "price") {
        list.sort((a, b) => {
            if (isup == true) {
                return a.price - b.price
            } else {
                return b.price - a.price
            }
        })
    }
    if (page && pageSize) {
        list = list.slice((page - 1) * pageSize, page * pageSize)
    }
    res.send({
        list,
        total
    })
})
var UPLOAD_DIR = path.join(__dirname, "../upload")
router.post("/upload", async (req, res) => {
    let form = new multiparty.Form()
    form.parse(req, async (err, fields, files) => {
        if (err) {
            res.status(401).json({
                ok: false,
                msg: "上传失败"
            })
            return
        }
        const fileHash = fields.FileHash[0]
        const chunkHash = fields.chunkHash[0]
        const chunkPath = path.resolve(UPLOAD_DIR, fileHash)
        if (!fse.existsSync(chunkPath)) {
            await fse.mkdirs(chunkPath)
        }
        const oldPath = files["chunk"][0].path
        await fse.move(oldPath, path.resolve(chunkPath, chunkHash))
        res.status(200).json({
            ok: true,
            msg: "上传成功"
        })
    })
})
const extraExt = filename => {
    return filename.slice(filename.lastIndexOf("."), filename.length)
}
router.post("/merge", async (req, res) => {
    const { FileHash, FileName, size } = req.body
    //如果已经存在该文件，就没必要合并了
    const filePath = path.resolve(UPLOAD_DIR, FileHash + extraExt(FileName))
    if (fse.existsSync(filePath)) {
        res.status(200).json({
            ok: true,
            msg: "文件已存在"
        })
        return
    }
    //如果不存在该文件，才去合并。
    const chunkDir = path.resolve(UPLOAD_DIR, FileHash)
    if (!fse.existsSync(chunkDir)) {
        res.status(401).json({
            ok: false,
            msg: "文件不存在"
        })
        return
    }
    //合并操作
    let chunkPaths = await fse.readdir(chunkDir)
    chunkPaths.sort((a, b) => a.split("_")[1] - b.split("_")[1])
    console.log(chunkPaths.length)
    const list = chunkPaths.map((chunkName, index) => {
        return new Promise(resolve => {
            const chunkPath = path.resolve(chunkDir, chunkName)
            const readStream = fse.createReadStream(chunkPath)
            const writeStream = fse.createWriteStream(filePath, {
                start: index * size,
                end: (index + 1) * size
            })
            readStream.on("end", async () => {
                await fse.unlink(chunkPath)
                resolve()
            })
            readStream.pipe(writeStream)
        })

    })
    await Promise.all(list)
    await fse.remove(chunkDir)
    res.status(200).json({
        ok: true,
        msg: "上传成功"
    })
})
router.post("/verify",async(req,res)=>{
    const {FileHash,FileName}=req.body
    const filePath=path.resolve(UPLOAD_DIR,FileHash+extraExt(FileName))
    const chunkDir=path.resolve(UPLOAD_DIR,FileHash)
    let chunkPaths = [] 
    if(fse.existsSync(chunkDir)){
        chunkPaths = await fse.readdir(chunkDir) //读取所有的分片名字
    }
    if(fse.existsSync(filePath)){
        res.status(200).json({
            ok:true,
            data:{
                shouldUpload:false
            }
        })
        
    }else{
        res.status(200).json({
            ok:true,
            data:{
                shouldUpload:true,
                existChunks:chunkPaths
            }
        })
    }
})
module.exports = router;
